# 课程中心微服务端到端测试运行脚本 (PowerShell版本)

param(
    [string]$Mode = "interactive",
    [string]$Spec = "",
    [switch]$Headless,
    [switch]$Help
)

# 显示帮助信息
if ($Help) {
    Write-Host "课程中心微服务端到端测试运行脚本" -ForegroundColor Green
    Write-Host ""
    Write-Host "用法:" -ForegroundColor Yellow
    Write-Host "  .\run-e2e-tests.ps1 [参数]"
    Write-Host ""
    Write-Host "参数:" -ForegroundColor Yellow
    Write-Host "  -Mode <模式>     测试运行模式: interactive, run, headless"
    Write-Host "  -Spec <文件>     运行特定的测试文件"
    Write-Host "  -Headless        运行无头模式测试"
    Write-Host "  -Help           显示此帮助信息"
    Write-Host ""
    Write-Host "示例:" -ForegroundColor Yellow
    Write-Host "  .\run-e2e-tests.ps1                    # 交互模式"
    Write-Host "  .\run-e2e-tests.ps1 -Mode run          # 运行所有测试"
    Write-Host "  .\run-e2e-tests.ps1 -Headless          # 无头模式"
    Write-Host "  .\run-e2e-tests.ps1 -Spec auth.cy.js   # 运行特定测试"
    exit 0
}

Write-Host "================================================" -ForegroundColor Cyan
Write-Host "课程中心微服务端到端测试运行脚本" -ForegroundColor Cyan
Write-Host "================================================" -ForegroundColor Cyan

# 检查执行策略
$executionPolicy = Get-ExecutionPolicy
if ($executionPolicy -eq "Restricted") {
    Write-Host "[警告] PowerShell执行策略被限制" -ForegroundColor Yellow
    Write-Host "请运行: Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser" -ForegroundColor Yellow
    Write-Host "或者使用管理员权限运行此脚本" -ForegroundColor Yellow
}

# 检查Node.js环境
Write-Host "检查Node.js环境..." -ForegroundColor Green
try {
    $nodeVersion = node --version 2>$null
    if ($nodeVersion) {
        Write-Host "[信息] Node.js版本: $nodeVersion" -ForegroundColor Green
    } else {
        throw "Node.js未找到"
    }
} catch {
    Write-Host "[错误] 未找到Node.js，请先安装Node.js" -ForegroundColor Red
    exit 1
}

# 检查npm环境
Write-Host "检查npm环境..." -ForegroundColor Green
try {
    $npmVersion = npm --version 2>$null
    if ($npmVersion) {
        Write-Host "[信息] npm版本: $npmVersion" -ForegroundColor Green
    } else {
        throw "npm未找到"
    }
} catch {
    Write-Host "[错误] 未找到npm，请检查Node.js安装" -ForegroundColor Red
    exit 1
}

# 进入前端目录
$scriptPath = Split-Path -Parent $MyInvocation.MyCommand.Path
$frontendPath = Split-Path -Parent $scriptPath
Set-Location $frontendPath
Write-Host "当前工作目录: $(Get-Location)" -ForegroundColor Green

# 检查必要文件
if (-not (Test-Path "package.json")) {
    Write-Host "[错误] 未找到package.json文件" -ForegroundColor Red
    exit 1
}

if (-not (Test-Path "cypress.config.js")) {
    Write-Host "[错误] 未找到cypress.config.js文件" -ForegroundColor Red
    exit 1
}

Write-Host ""
Write-Host "================================================" -ForegroundColor Cyan
Write-Host "第一步: 检查依赖项" -ForegroundColor Cyan
Write-Host "================================================" -ForegroundColor Cyan

# 检查Cypress是否已安装
$cypressInstalled = $false
try {
    $cypressCheck = npm list cypress 2>$null
    if ($LASTEXITCODE -eq 0) {
        $cypressInstalled = $true
        Write-Host "[信息] Cypress已安装" -ForegroundColor Green
    }
} catch {}

if (-not $cypressInstalled) {
    Write-Host "[警告] Cypress未安装，正在安装..." -ForegroundColor Yellow
    npm install cypress --save-dev
    if ($LASTEXITCODE -ne 0) {
        Write-Host "[错误] Cypress安装失败" -ForegroundColor Red
        exit 1
    }
    Write-Host "[信息] Cypress安装完成" -ForegroundColor Green
}

Write-Host ""
Write-Host "================================================" -ForegroundColor Cyan
Write-Host "第二步: 检查后端服务状态" -ForegroundColor Cyan
Write-Host "================================================" -ForegroundColor Cyan

# 检查API网关
Write-Host "检查API网关 (http://localhost:8080)..." -ForegroundColor Green
try {
    $response = Invoke-WebRequest -Uri "http://localhost:8081/actuator/health" -TimeoutSec 5 -ErrorAction Stop
    if ($response.StatusCode -eq 200) {
        Write-Host "[信息] API网关运行正常" -ForegroundColor Green
    }
} catch {
    Write-Host "[警告] API网关似乎未运行，请确保后端服务已启动" -ForegroundColor Yellow
    Write-Host ""
    Write-Host "启动后端服务的方法:" -ForegroundColor Yellow
    Write-Host "1. 进入后端目录: cd ..\backend\microservices" -ForegroundColor Yellow
    Write-Host "2. 运行: docker-compose up -d" -ForegroundColor Yellow
    Write-Host "或者运行: .\start-all-services.bat" -ForegroundColor Yellow
    Write-Host ""
    
    $continue = Read-Host "是否继续运行测试? (y/n)"
    if ($continue -ne "y") {
        Write-Host "测试已取消" -ForegroundColor Yellow
        exit 1
    }
}

# 检查各个微服务
$services = @(
    @{Name="用户管理服务"; Port=8082},
    @{Name="课程管理服务"; Port=8083},
    @{Name="练习管理服务"; Port=8084},
    @{Name="学习进度服务"; Port=8085}
)

foreach ($service in $services) {
    Write-Host "检查$($service.Name) (http://localhost:$($service.Port))..." -ForegroundColor Green
    try {
        $response = Invoke-WebRequest -Uri "http://localhost:$($service.Port)/actuator/health" -TimeoutSec 3 -ErrorAction Stop
        if ($response.StatusCode -eq 200) {
            Write-Host "[信息] $($service.Name)运行正常" -ForegroundColor Green
        }
    } catch {
        Write-Host "[警告] $($service.Name)可能未运行" -ForegroundColor Yellow
    }
}

Write-Host ""
Write-Host "================================================" -ForegroundColor Cyan
Write-Host "第三步: 运行测试" -ForegroundColor Cyan
Write-Host "================================================" -ForegroundColor Cyan

# 如果指定了无头模式
if ($Headless) {
    $Mode = "headless"
}

# 根据模式运行测试
switch ($Mode.ToLower()) {
    "headless" {
        Write-Host "[信息] 运行无头模式测试..." -ForegroundColor Green
        if ($Spec) {
            npx cypress run --headless --spec "cypress/e2e/$Spec"
        } else {
            npx cypress run --headless
        }
    }
    "run" {
        Write-Host "[信息] 运行所有测试..." -ForegroundColor Green
        if ($Spec) {
            npx cypress run --spec "cypress/e2e/$Spec"
        } else {
            # 按顺序运行测试
            $testFiles = @(
                "auth.cy.js",
                "course.cy.js", 
                "course_content.cy.js",
                "exercise.cy.js",
                "user_center_enhanced.cy.js",
                "learning_records.cy.js"
            )
            
            $totalTests = $testFiles.Count
            $currentTest = 1
            
            foreach ($testFile in $testFiles) {
                Write-Host "[$currentTest/$totalTests] 运行 $testFile..." -ForegroundColor Green
                npx cypress run --spec "cypress/e2e/$testFile" --reporter json --reporter-options "toConsole=false"
                $currentTest++
            }
        }
    }
    "interactive" {
        Write-Host "[信息] 打开Cypress测试界面..." -ForegroundColor Green
        npx cypress open
    }
    default {
        # 交互模式选择
        Write-Host "请选择测试运行模式:" -ForegroundColor Yellow
        Write-Host "1. 无头模式 (headless) - 适合CI/CD" -ForegroundColor White
        Write-Host "2. 有界面模式 (headed) - 适合调试" -ForegroundColor White
        Write-Host "3. 交互模式 - 打开Cypress测试界面" -ForegroundColor White
        Write-Host "4. 运行特定测试文件" -ForegroundColor White
        Write-Host "5. 运行所有测试 (推荐)" -ForegroundColor White
        
        $choice = Read-Host "请输入选择 (1-5)"
        
        switch ($choice) {
            "1" { 
                npx cypress run --headless 
            }
            "2" { 
                npx cypress run 
            }
            "3" { 
                npx cypress open 
            }
            "4" {
                Write-Host ""
                Write-Host "可用的测试文件:" -ForegroundColor Yellow
                Write-Host "1. auth.cy.js - 用户认证测试" -ForegroundColor White
                Write-Host "2. course.cy.js - 课程管理测试" -ForegroundColor White
                Write-Host "3. exercise.cy.js - 练习模块测试" -ForegroundColor White
                Write-Host "4. user_center.cy.js - 用户中心测试" -ForegroundColor White
                Write-Host "5. user_password_change.cy.js - 密码修改测试" -ForegroundColor White
                Write-Host "6. course_inside.cy.js - 课程内部测试" -ForegroundColor White
                Write-Host "7. learning_records.cy.js - 学习记录测试 (新)" -ForegroundColor White
                Write-Host "8. user_center_enhanced.cy.js - 增强用户中心测试 (新)" -ForegroundColor White
                Write-Host "9. course_content.cy.js - 课程内容测试 (新)" -ForegroundColor White
                
                $fileChoice = Read-Host "请选择要运行的测试文件编号"
                
                $testFiles = @{
                    "1" = "auth.cy.js"
                    "2" = "course.cy.js"
                    "3" = "exercise.cy.js"
                    "4" = "user_center.cy.js"
                    "5" = "user_password_change.cy.js"
                    "6" = "course_inside.cy.js"
                    "7" = "learning_records.cy.js"
                    "8" = "user_center_enhanced.cy.js"
                    "9" = "course_content.cy.js"
                }
                
                if ($testFiles.ContainsKey($fileChoice)) {
                    $selectedFile = $testFiles[$fileChoice]
                    Write-Host "[信息] 运行测试文件: $selectedFile" -ForegroundColor Green
                    npx cypress run --spec "cypress/e2e/$selectedFile"
                } else {
                    Write-Host "[错误] 无效的选择" -ForegroundColor Red
                }
            }
            "5" {
                # 运行所有测试的逻辑已在上面的 "run" 模式中实现
                & $MyInvocation.MyCommand.Path -Mode "run"
            }
            default {
                Write-Host "[错误] 无效的选择" -ForegroundColor Red
            }
        }
    }
}

Write-Host ""
Write-Host "================================================" -ForegroundColor Cyan
Write-Host "测试完成" -ForegroundColor Cyan
Write-Host "================================================" -ForegroundColor Cyan

# 检查测试结果
if (Test-Path "cypress\results") {
    Write-Host "[信息] 测试结果已保存到 cypress\results 目录" -ForegroundColor Green
}

if (Test-Path "cypress\screenshots") {
    Write-Host "[信息] 测试截图已保存到 cypress\screenshots 目录" -ForegroundColor Green
}

if (Test-Path "cypress\videos") {
    Write-Host "[信息] 测试视频已保存到 cypress\videos 目录" -ForegroundColor Green
}

Write-Host ""
Write-Host "[信息] 端到端测试执行完成" -ForegroundColor Green
Write-Host "[提示] 如果测试失败，请检查:" -ForegroundColor Yellow
Write-Host "  1. 后端微服务是否正常运行" -ForegroundColor White
Write-Host "  2. 数据库是否已正确初始化" -ForegroundColor White
Write-Host "  3. 测试数据是否存在" -ForegroundColor White
Write-Host "  4. 网络连接是否正常" -ForegroundColor White
Write-Host ""

# 如果不是交互模式，暂停以便查看结果
if ($Mode -ne "interactive") {
    Read-Host "按回车键退出"
}
